//
//  NSDate+Timestamp.m
//  高仿暴走斗图
//
//  Created by huangsongyao on 16/3/7.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "NSDate+Timestamp.h"
#import "NSDate+TimeManager.h"

static NSInteger _TimeSp = 1000;                 //时间戳倍数

@implementation NSDate (Timestamp)

#pragma mark - New Date To Show Timestamp(Seconds)

+ (unsigned long long)timestampMillisecond {
    
    return (unsigned long long)([[NSDate date] timeIntervalSince1970] * _TimeSp);
}

#pragma mark - New Date To Show String

+ (NSString *)timestampString {
    
    return [NSString stringWithFormat:@"%lld",[NSDate timestampMillisecond]];
}

#pragma mark - Timestamp Change To Date

- (NSTimeInterval)timespChangeToDateWithTimespString:(NSString *)timespString {
    
    NSDate *date = [NSDate dateyyyyMMddHHmmssFromString:timespString];
    NSTimeInterval timestamp = [date timeIntervalSince1970] * _TimeSp;
    return timestamp;
}

- (NSDate *)timestampChangeToDateWithTimesp:(NSTimeInterval)timesp {
    
    NSDate *conforTimesp = [NSDate dateWithTimeIntervalSince1970:timesp/_TimeSp];
    return conforTimesp;
}

#pragma mark - Compare Timestamp

+ (NSDateComponents *)compareTimestampWithStartTime:(NSDate *)starTime endDate:(NSDate *)endDate {
    
    if (!starTime || !endDate) {
        return nil;
    }
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [gregorian setFirstWeekday:1];
    
    //去掉时分秒信息
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:starTime];
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    
    return dayComponents;
    
}

+ (NSString *)passedTimeWithTimestamp:(NSNumber *)timestamp {
    
    if (timestamp.integerValue == 0) {
        return nil;
    }
    long long interval = (long long)(([self timestampMillisecond] - timestamp.longLongValue) / _TimeSp);
    NSString *suffix = HSYLOCALIZED(@"前");
    if (interval <= 0) {
        interval = -interval;
        suffix = HSYLOCALIZED(@"后");
    }
    
    NSArray *timeValues = @[@(D_MINUTE), @(D_MINUTE), @(24), @(30), @(12), @(1000000000)];
    NSArray *timeNames  = @[HSYLOCALIZED(@"秒"), HSYLOCALIZED(@"分钟"), HSYLOCALIZED(@"小时"), HSYLOCALIZED(@"天"), HSYLOCALIZED(@"个月"), HSYLOCALIZED(@"年")];
    
    for (int i = 0; i < timeValues.count; i++) {
        if (interval / [timeValues[i] longLongValue] <= 0) {
            return [NSString stringWithFormat:@"%lli%@%@", interval, timeNames[i], suffix];
        } else {
            interval /= [timeValues[i] longLongValue];
        }
    }
    
    return nil;
}

@end
